package performace_test;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;

import set.CandyAVLSet;
import set.CandyBSTSet;
import set.CandyLinkedListSet;
import set.CandySet;
import set.CandyTrieSet;
import util.FileOperation;

/**
 * 
 * @Title: SetPerformaceTest.java 
 * @Package performace_test 
 * @Description: CandyBSTSet和CandyLinkedListSet性能测试以及对比
 * @author CandyWall   
 * @date 2021年1月6日 下午1:06:49 
 * @version V1.0
 */
public class SetPerformaceTest {
    /**
     * 测试集合添加元素的性能，返回总共消耗的时间（秒）
     * @param queue     ：需要进行性能测试的队列
     * @param opCount   ：需要进行出入队的次数
     * @return
     */
    public static double testSet(ArrayList<String> words, CandySet<String> set) {
        // 记录开始时间
        long startTime = System.nanoTime();
        for(String word : words) {
            set.add(word);
        }
        for(String word : words) {
            set.contains(word);
        }
        System.out.println("单词总数：" + words.size());
        System.out.println("不同单词数量：" + set.getSize());
        // 返回耗时
        return (System.nanoTime() - startTime) / 1000_000_000.0;
    }
    
    // 从文件中读取到所有的单词，并以ArrayList<String>方式返回
    private static ArrayList<String> readWordsFromFile(String filePath) {
        ArrayList<String> words = new ArrayList<>();
        if(!FileOperation.readFile(filePath, words)) {
            // 加载失败
            try {
                throw new FileNotFoundException("找不到文件");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } 
        return words;
    }
    
    public static void main(String[] args) {
        String filePath = "testData/pride-and-prejudice.txt";
        ArrayList<String> words = readWordsFromFile(filePath);
        Collections.sort(words);
        
        // 进行性能测试
        double cost1 = testSet(words, new CandyBSTSet<String>());
        System.out.println("CandyBSTSet耗时：" + cost1 + " 秒");
        System.out.println("----------------------------------------");
        double cost2 = testSet(words, new CandyLinkedListSet<String>());
        System.out.println("CandyLinkedListSet耗时：" + cost2 + " 秒");
        System.out.println("----------------------------------------");
        double cost3 = testSet(words, new CandyTrieSet());
        System.out.println("CandyTrieSet耗时：" + cost3 + " 秒");
        System.out.println("----------------------------------------");
        double cost4 = testSet(words, new CandyAVLSet<String>());
        System.out.println("CandyAVLSet耗时：" + cost4 + " 秒");
        System.out.println("----------------------------------------");
        //System.out.println("CandyBSTSet和CandyLinkedListSet性能比（性能和耗时成反比）：" + cost2 / cost1);
    }
}
